package com.kzw.misc.log;

import java.lang.reflect.Method;
import java.util.Date;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;

import com.kzw.misc.utils.ContextUtil;
import com.kzw.oa.system.model.AppUser;
import com.kzw.oa.system.model.SystemLog;
import com.kzw.oa.system.service.SystemLogService;

/**
  * 定义一个日志切面
 * 
 */
public class LogAspect {

	@Resource
	private SystemLogService systemLogService;

	private Log logger = LogFactory.getLog(LogAspect.class);

	/**
	 * 环绕通知
	 */
	public Object doSystemLog(ProceedingJoinPoint point) throws Throwable {

		String methodName = point.getSignature().getName();
		// 目标方法不为空
		if (StringUtils.isNotEmpty(methodName)) {
			// set与get方法除外
			if (!(methodName.startsWith("set") || methodName.startsWith("get"))) {

				Class<?> targetClass = point.getTarget().getClass();
				Method method = targetClass.getMethod(methodName);

				if (method != null) {
					// 是否有Action注解
					boolean hasAnnotation = method.isAnnotationPresent(Action.class);
					if (hasAnnotation) {
						Action annotation = method.getAnnotation(Action.class);

						String methodDescp = annotation.desc();
						if (logger.isDebugEnabled()) {
							logger.debug("Action method:" + method.getName() + " Description:" + methodDescp);
						}
						
						// 取到当前的操作用户
						AppUser appUser = ContextUtil.getCurrentUser();
						if (appUser != null) {
							try {
								SystemLog sysLog = new SystemLog();
								sysLog.setCreatetime(new Date());
								sysLog.setUserId(appUser.getUserId());
								sysLog.setUsername(appUser.getFullname());
								sysLog.setExeOperation(methodDescp);
								systemLogService.saveOrUpdate(sysLog);
							} catch (Exception ex) {
								logger.error(ex.getMessage());
							}
						}

					}
				}

			}
		}
		return point.proceed();
	}

}
